package javase.javase02.thread;

/**
 * @author: Gan
 * @date 2021/4/22 0022 14:18
 * @description: **1.启动2个线程 打印100个数 **
 * 线程a 打印 1 3 5 7 9 奇数
 * 线程b 打印 2 4 6 8 10 偶数
 * 分析：线程a打印的是奇数 线程b打印的是偶数
 **/
public class Day21Work01 {
    public static void main(String[] args) throws InterruptedException {
        PrintNum pn = new PrintNum();
        Thread a = new Thread(pn);
        Thread b = new Thread(pn);
        a.setName("a线程");
        a.join();
        a.start();
        Thread.sleep(100);
        b.setName("b线程");
        b.start();
    }
}

class PrintNum implements Runnable {
    private int num = 1;
    Object obj = new Object();
    @Override
    public void run() {
        while (true) {
            synchronized (obj) {
                //唤醒另外一个进程
                obj.notify();
                if (num <= 100) {
                    System.out.println(Thread.currentThread().getName() + "打印:" + num);
                    num++;
                    //将自己阻塞挂起，等另外一个线程执行
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }

        }
    }
}